﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using ShpMerger;
using System.IO;
using Microsoft.Win32;
using System.Collections.ObjectModel;
using Regedit;

namespace ShpMergerGui
{
    public partial class MergeShapeFile : Form
    {
        const int fileOrFolderTotallCount = 10;  // record the file or folder count ihe regedit.
        int Progress = 0;
        string[] files;
        string mergeFile;
        string sourceDerectiony;
        delegate void Updatecontrl();

        public MergeShapeFile()
        {
            InitializeComponent();
            InitializeBackgoundWorker();
        }

        private void InitializeBackgoundWorker()
        {
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            try
            {
                ShapeFileMerger shapeFileMerger = new ShapeFileMerger();
                shapeFileMerger.Merge(files, mergeFile, worker, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Merge error,error code:" + ex.ToString(), "Information", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        //If hide the progressbar use the code
        //private void Updateprogress()
        //{
        //    this.progressBar1.Visible = false;
        //}

        private void UpdatepLabel()
        {
            this.lblPercent.Text = "";
            this.lblPercent.Visible = false;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            btnMerge.Enabled = false;
            btnCancel.Enabled = true;
            this.progressBar1.Value = e.ProgressPercentage;
            Progress = e.ProgressPercentage;
            this.lblPercent.Text = Progress.ToString() + "%";
            toolStripStatusLabel1.Text = "Complete" + Progress.ToString() + "%";
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("Cancel merge，complte" + Progress.ToString() + "%.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Merge success.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //If hide the progressbar use the code
                //this.progressBar1.Invoke(new Updatecontrl(Updateprogress));

                this.lblPercent.Invoke(new Updatecontrl(UpdatepLabel));
            }
            this.btnMerge.Enabled = true;
            this.btnCancel.Enabled = false;
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                cbxFolder.Text = dialog.SelectedPath;
            }
            dialog.Dispose();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Shape Files|*.shp";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                cbxFile.Text = dialog.FileName;
            }
            dialog.Dispose();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.backgroundWorker1.CancelAsync();
            btnCancel.Enabled = false;
            btnMerge.Enabled = true;
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            sourceDerectiony = cbxFolder.Text.Trim();
            mergeFile = cbxFile.Text.Trim();
            if ((sourceDerectiony.Length <= 0) || (mergeFile.Length <= 0))
            {
                MessageBox.Show("SourceFolder or TargetFile is null.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
                if (!Directory.Exists(sourceDerectiony))
                {
                    MessageBox.Show("SourceFolder not exist.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                files = Directory.GetFiles(sourceDerectiony, "*.shp");
                if (files.Length <= 1)
                {
                    MessageBox.Show("Merge file less 1.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
            }
            Progress = 0;
            backgroundWorker1.RunWorkerAsync();
            this.lblPercent.Text = "";
            this.toolStripStatusLabel1.Text = "";
            this.lblPercent.Visible = true;
            this.progressBar1.Visible = true;
            btnCancel.Enabled = true;

            // Write the folder name  and file name to regedit. 
            RegeditReadAndWrite regeditReadAndWrite = new RegeditReadAndWrite(10);
            regeditReadAndWrite.WriteRegedit("Folder", sourceDerectiony);
            regeditReadAndWrite.WriteRegedit("File", mergeFile);

            // Initialization the folder droplist and file droplist.
            initializationFolderAndFile();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("You sure exit?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text.ToString())
            {
                case "OpenFolder":
                    btnFind_Click(sender, e);
                    break;
                case "SaveFile":
                    btnSave_Click(sender, e);
                    break;
                case "Merge":
                    btnMerge_Click(sender, e);
                    break;
                case "Cancel":
                    btnCancel_Click(sender, e);
                    break;
                case "Exit":
                    btnExit_Click(sender, e);
                    break;
                default:
                    break;
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text.ToString())
            {
                case "OpenFolder":
                    btnFind_Click(sender, e);
                    break;
                case "SaveFile":
                    btnSave_Click(sender, e);
                    break;
                case "Merge":
                    btnMerge_Click(sender, e);
                    break;
                case "Cancel":
                    btnCancel_Click(sender, e);
                    break;
                case "Exit":
                    btnExit_Click(sender, e);
                    break;
                default:
                    break;
            }
        }

        public void initializationFolderAndFile()
        {
            // Read the folder name  and file name to regedit. 
            RegeditReadAndWrite regeditReadAndWrite = new RegeditReadAndWrite(10);
            Collection<string> Folder = regeditReadAndWrite.ReadRegedit("Folder");
            Collection<string> File = regeditReadAndWrite.ReadRegedit("File");
            cbxFolder.Items.Clear();
            cbxFile.Items.Clear();
            if (Folder != null)
            {
                foreach (string item in Folder)
                {
                    cbxFolder.Items.Add(item);
                }
                cbxFolder.SelectedIndex = 0;
            }
            if (File != null)
            {
                foreach (string item in File)
                {
                    cbxFile.Items.Add(item);
                }
                cbxFile.SelectedIndex = 0;
            }
        }

        private void MergeShapeFile_Load(object sender, EventArgs e)
        {
            initializationFolderAndFile();
        }

        private void cbxFile_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnMerge_Click(sender, e);
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnFind_Click(sender, e);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnExit_Click(sender, e);
        }

        private void mergeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnMerge_Click(sender, e);
        }

        private void cancelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnCancel_Click(sender, e);
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnSave_Click(sender, e);
        }
    }
}
